package com.zipou.myMail;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;

public class MyMailServiceImpl implements MyMailService {

	private Logger log = Logger.getAnonymousLogger();

	private Properties config  = new Properties();

	private Session session;

	//	private Transport transport;

	public MyMailServiceImpl() {
		try {
			InputStream f = this.getClass().getResourceAsStream("/mail.properties");
			config.load(f);

			// Get system properties
			Properties props = System.getProperties();

			// Setup mail server
			props.put("mail.smtp.host", getConfig("smtpHost"));
			//	        props.put("mail.smtp.starttls.enable",getConfig("useTls"));
			props.put("mail.smtp.port", getConfig("smtpPort"));

			if (getConfig("useSsl").equals("true")) {
				props.put("mail.smtp.socketFactory.port", getConfig("smtpPort"));
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
				props.put("mail.smtp.socketFactory.fallback", "false");
			}

			if (getConfig("useAuth").equals("true")) {
				props.put("mail.smtp.auth", getConfig("useAuth"));  // If you need to authenticate
				session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(getConfig("userLogin").toString(), getConfig("userPass").toString());
					}
				});	
			} else {
				session = Session.getDefaultInstance(props, null);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private Object getConfig(String key) {
		return this.config.get(key);
	}

	public final void send(MyMailMessage m) throws MyMailServiceException {
		try {
			String from = getConfig("smtpFrom").toString();
			log.info("Envoi mail From: " + from);
			m.setFrom(new InternetAddress(from));

			Transport.send(m);
		} catch (MessagingException e) {
			throw new MyMailServiceException("Erreur a l'envoi: " + e.getMessage());
		}
	}

	//	public Transport getTransport() {
	//		return this.transport;
	//	}

	public final Session getSession() {
		return session;
	}

	public static void main(String args[]) {
		MyMailServiceImpl mailService = new MyMailServiceImpl();
		try {
			MyMailMessage m = new MyMailMessage(mailService.getSession());
			m.setHtml("<html><b>Coucou</b> toi</html>");
			//			m.addAttachement(new MyFileDataSource("D://go.pdf", "application/pdf"), "alice.pdf");
			m.addDest("romain@fenninger.fr");
			mailService.send(m);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
